package client.popups.meeting;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Calendar;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;

import miscellaneous.Storage;
import miscellaneous.TimeSupport;

import data.Invite;
import data.Meeting;
import data.Message;
import data.SynchronizedList;
import data.User;
import data.room.Room;
import javax.swing.JList;
import javax.swing.JScrollPane;

import client.popups.appointment.RoomOverview;

/**
 *  Takes a meeting as argument and shows the values stored, and
 *  makes it possible to change each one.
 * @author Patrick and Daniel
 *
 */

public class MeetingOverview  extends JFrame implements PropertyChangeListener{

	private JPanel contentPane;
	private JTextField textStartTime;
	private JTextField textEndTime;
	private JTextField textStartDate;
	private JTextField textLocation;
	private JTextField textTitle;
	private JTextPane textPane;
	private JButton deleteButton;
	private JButton saveButton;
	private JButton acceptButton; 
	private JButton roomChooser;
	private JList list;
	private JButton addParticipantButton;
	private DefaultListModel participantsModel;
	private JLabel meetLeader;

	private Room room;	
	private Meeting meeting; 
	
	private RoomOverview roomOverviewPanel;
	private ParticipantsOverview participantsOverviewPanel;
	
	private SynchronizedList<Message> messages;

	/**
	 * Create the frame.
	 */
	public MeetingOverview(Meeting meet){
		
		setIconImage(Toolkit.getDefaultToolkit().getImage("resources/icons/aCalendarIcon.png"));
		setTitle("Møteoversikt");
		this.meeting = meet;
		this.room = meet.getReservation().getRoom();
		messages = Storage.messages;
		
		Storage.addListener(this);
		
		//Add each participant of the meeting in to the list 
		participantsModel = new DefaultListModel();

		setResizable(false);
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 449, 565);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JLabel lblSted = new JLabel("Sted:");
		lblSted.setBounds(201, 63, 46, 14);
		contentPane.add(lblSted);

		JLabel lblBeskrivelse = new JLabel("Beskrivelse:");
		lblBeskrivelse.setBounds(31, 121, 98, 14);
		contentPane.add(lblBeskrivelse);

		textPane = new JTextPane();
		textPane.setBounds(31, 138, 387, 147);
		contentPane.add(textPane);

		deleteButton = new JButton();
		deleteButton.setBounds(10, 503, 104, 23);
		contentPane.add(deleteButton);
		
		if(isOwner()) {
			deleteButton.setText("Slett");
			deleteButton.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					deleteAppointment();
				}
			});
		
		} else {
			deleteButton.setText("Avslå");
			deleteButton.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					for (Message m : messages) {
						if(m instanceof Invite && m.getReceiver() == Storage.getloggedInUser() && m.getMeeting() == meeting){
							Invite i = (Invite) m;
							i.reject();
						}
					}
					closeWindow();
				}
			});
		}

		saveButton = new JButton();
		saveButton.setBounds(276, 503, 142, 23);
		contentPane.add(saveButton);

		if(isOwner()) {
			saveButton.setText("Lagre og lukk");
			saveButton.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					String datestart = textStartTime.getText() + ":00 " + textStartDate.getText();
					String dateend = textEndTime.getText() + ":00 " + textStartDate.getText();
					Calendar gcStart = TimeSupport.convertStringDateToCalendar(datestart);
					Calendar gcEnd = TimeSupport.convertStringDateToCalendar(dateend);
					if(gcStart.getTimeInMillis() > gcEnd.getTimeInMillis() || 
							gcEnd.getTimeInMillis() < gcStart.getTimeInMillis()){
						JOptionPane.showMessageDialog(null, "Ugyldig tidspunkt");
					}else{
						updateObjectFromGUI();
						closeWindow();
					}
				}
			});

		} else {
			saveButton.setText("Lukk");
			saveButton.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					closeWindow();	
				}
			});
		}

		roomChooser = new JButton("Velg rom");
		roomChooser.setBounds(79, 58, 117, 25);
		contentPane.add(roomChooser);

		roomChooser.addActionListener(new ActionListener() {	
			@Override
			public void actionPerformed(ActionEvent arg0) {
				openRoomSelectioner();
			}
		});

		JLabel lblRom = new JLabel("Rom");
		lblRom.setBounds(31, 63, 49, 15);
		contentPane.add(lblRom);

		JLabel lblStart = new JLabel("Start:");
		lblStart.setBounds(31, 2, 59, 14);
		contentPane.add(lblStart);

		JLabel lblSlutt = new JLabel("Slutt:");
		lblSlutt.setBounds(31, 32, 59, 14);
		contentPane.add(lblSlutt);

		JLabel lblTittel = new JLabel("Tittel:");
		lblTittel.setBounds(32, 94, 59, 14);
		contentPane.add(lblTittel);

		textStartTime = new JTextField();
		textStartTime.setBounds(99, 0, 63, 28);
		contentPane.add(textStartTime);
		textStartTime.setColumns(10);

		textEndTime = new JTextField();
		textEndTime.setBounds(99, 26, 63, 28);
		contentPane.add(textEndTime);
		textEndTime.setColumns(10);

		textStartDate = new JTextField();
		textStartDate.setBounds(250, 13, 92, 28);
		contentPane.add(textStartDate);
		textStartDate.setColumns(10);

		textLocation = new JTextField();
		textLocation.setBounds(249, 61, 169, 28);
		contentPane.add(textLocation);
		textLocation.setColumns(10);

		textTitle = new JTextField();
		textTitle.setBounds(79, 92, 339, 31);
		contentPane.add(textTitle);
		textTitle.setColumns(10);
		
		JLabel lblDeltakere = new JLabel("Deltakere:");
		lblDeltakere.setBounds(31, 319, 98, 14);
		contentPane.add(lblDeltakere);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(31, 335, 387, 130);
		contentPane.add(scrollPane);
		
		list = new JList(participantsModel);
		list.setCellRenderer(new ParticipantRenderer(meeting));
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		scrollPane.setViewportView(list);
		
		addParticipantButton = new JButton("Endre deltakere");
		addParticipantButton.setBounds(31, 468, 117, 23);
		addParticipantButton.addActionListener(new ButtonActionListener());
		contentPane.add(addParticipantButton);
		
		JLabel labelMeetLeader = new JLabel("M\u00F8teleder:");
		labelMeetLeader.setBounds(31, 297, 80, 16);
		contentPane.add(labelMeetLeader);
		
		meetLeader = new JLabel("");
		meetLeader.setBounds(99, 297, 55, 16);
		contentPane.add(meetLeader);
		
		acceptButton = new JButton("Godta");
		acceptButton.addActionListener(new ButtonActionListener());
		acceptButton.setBounds(132, 503, 90, 28);
		contentPane.add(acceptButton);
		
		JLabel lblDato = new JLabel("Dato:");
		lblDato.setBounds(193, 17, 55, 16);
		contentPane.add(lblDato);

		if(!isOwner()) {
			textStartTime.setEditable(false);
			textEndTime.setEditable(false);
			textStartDate.setEditable(false);
//			textEndDate.setEditable(false);
			textLocation.setEditable(false);
			textTitle.setEditable(false);
			textPane.setEditable(false);
			roomChooser.setEnabled(false);
			addParticipantButton.setEnabled(false);
//			if(!meeting.getParticipants().contains(Storage.getloggedInUser())) deleteButton.setEnabled(false);
		}
		
		setValuesToGUI();
	}

	/**
	 * Sets the correct value to the GUI (fields) based on the object(s).
	 */
	public void setValuesToGUI() {
		if(meeting != null) {
			if(meeting.getReservation().getStartTime() != null) {
				textStartTime.setText(TimeSupport.showTimeNice(
						meeting.getReservation().getStartTime()));
				textStartDate.setText(TimeSupport.showDateNice(
						meeting.getReservation().getStartTime()));	
			}
			if(meeting.getReservation().getEndTime() != null) {
				textEndTime.setText(TimeSupport.showTimeNice(
						meeting.getReservation().getEndTime()));
//				textEndDate.setText(TimeSupport.showDateNice(
//						meeting.getReservation().getEndTime()));
			}
			if(meeting.getTitle() != null) {
				textTitle.setText(meeting.getTitle());
			}
			if(meeting.getOwner() != null){
				meetLeader.setText(meeting.getOwner().getName());
			}
			if(meeting.getDescription() != null) {
				textPane.setText(meeting.getDescription());
			}
			if(meeting.getReservation().getRoom() != null) {
				roomChooser.setText(meeting.getReservation().
						getRoom().getName());
				textLocation.setText(meeting.getReservation().
						getRoom().getCasualName());
				textLocation.setEnabled(false);
			} else {
				if(meeting.getLocation() != null) {
					textLocation.setText(meeting.getLocation());
					textLocation.setEnabled(true);

				}
			}
			if(meeting.getParticipants() != null){
				for (User user : meeting.getParticipants()) {
					participantsModel.addElement(user);
				}
			}
		}
	}

	/**
	 * Updates the object with the values from GUI
	 */
	public void updateObjectFromGUI() {
		String datestart = textStartTime.getText() + ":00 " + textStartDate.getText();
		String dateend = textEndTime.getText() + ":00 " + textStartDate.getText();

		meeting.getReservation().updateAll(
				TimeSupport.convertStringDateToCalendar(datestart),
				TimeSupport.convertStringDateToCalendar(dateend), 
				room);

		meeting.UpdateAll(
				textTitle.getText(), textPane.getText(),
				textLocation.getText(), meeting.getReservation());

		JOptionPane.showMessageDialog(this, "Lagret");
		closeWindow();
	}

	/**
	 * Opens the a GUI where it is possible to select a available room
	 */
	public void openRoomSelectioner() {
//		JOptionPane.showMessageDialog(this, "Kode mangler: Skal åpne " +
//		"et valg av rom (fjern romreservasjon må være et valg)");
		if(this.room != null){
			roomOverviewPanel = new RoomOverview(this.room, this.meeting);		//send inn the current appointment to room selector
		} else {
			roomOverviewPanel = new RoomOverview(null, this.meeting);
		}
		roomOverviewPanel.addPropertyChangeListener(this);
		roomOverviewPanel.pack();
		roomOverviewPanel.setVisible(true);
		roomOverviewPanel.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	}

	public Room getRoom() {
		return room;
	}

	/**
	 * Aks if your sure, and is so deletes the appointment
	 */
	public void deleteAppointment() {
		Storage.meetings.remove(meeting);
		this.dispose();
	}

	/**
	 * Closes the window
	 */
	public void closeWindow() {
		this.dispose();
	}

	public void setRoom(Room room) {
		this.room = room;
	}

	private boolean isOwner() {
		return Storage.getloggedInUser() == meeting.getOwner();
	}


	public void addButtonProperties(){
		participantsOverviewPanel = new ParticipantsOverview(meeting.getParticipants());
		participantsOverviewPanel.addPropertyChangeListener(this);
		participantsOverviewPanel.pack();
		participantsOverviewPanel.setVisible(true);
		participantsOverviewPanel.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if(evt.getSource() instanceof Storage) {
			participantsModel.clear();
			if(meeting.getParticipants() != null){
				for (User user : meeting.getParticipants()) {
					participantsModel.addElement(user);
				}
			}
			list.validate();
			list.repaint();
		}
		if(evt.getPropertyName().equals("overviewUpdate")){
			this.room = (Room) evt.getNewValue();
			if(this.room != null){
				roomChooser.setText(this.room.getName());
				textLocation.setText(this.room.getCasualName());
				textLocation.setEnabled(false);
			} else {
				roomChooser.setText("");
				textLocation.setText("");
				textLocation.setEnabled(true);
			}
		} else if(evt.getPropertyName().equals("sendParticipantsList")){
			meeting.setParticipants((List<User>) evt.getNewValue());
			participantsModel.clear();
			if(meeting.getParticipants() != null){
				for (User user : meeting.getParticipants()) {
					participantsModel.addElement(user);
				}
			}
			list.validate();
			list.repaint();
		}
	}
	
	public class ButtonActionListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			if(e.getSource() == addParticipantButton){
				addButtonProperties();
			}else if(e.getSource() == acceptButton){
				for (Message m : messages) {
					if(m instanceof Invite && m.getReceiver() == Storage.getloggedInUser() && m.getMeeting() == meeting){
						Invite i = (Invite) m;
						i.accept();
					}
				}
				dispose();
			}
		}
		
	}
}